<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="100%" @ok="handleSubmit">
    <BasicForm @register="registerForm">
       <template #userInfo>
<!--         v-if="isUpdate"-->
         <Descriptions size="small" title=""
                       style="margin-top: 10px;" >

           <DescriptionsItem label="姓名">
             {{dataList.userName}}
           </DescriptionsItem>
           <DescriptionsItem label="性别">
             {{dataList.gender}}
           </DescriptionsItem>
           <DescriptionsItem label="出生日期">
             {{dataList.birthdate?util.formatDate(new Date(dataList.birthdate)):'' }}
           </DescriptionsItem>
           <DescriptionsItem label="入职日期">
             {{dataList.addTime?util.formatDate(new Date(dataList.addTime)):''}}
           </DescriptionsItem>
           <DescriptionsItem label="钉钉职位(仅参考)">
             {{dataList.roleName}}
           </DescriptionsItem>
         </Descriptions>
       </template>
      <template #items="{ model, field }">
        <vxe-grid ref="tableRef" v-bind="gridOptions" style="height: 200px;">
          <template #toolbar_buttons>
          </template>


        </vxe-grid>
      </template>
      <template #postRequestId="{ model, field }">
        <vxe-select v-model="model[field]" placeholder="请选择" clearable  filterable >
          <vxe-option :value="item.postRequestId" :label="item.value" v-for="(item,index) in requestList"></vxe-option>
        </vxe-select>
      </template>
      <template #satisfactions="{ model, field }">
        <vxe-grid ref="tableRef2" v-bind="gridOptions2" style="height: 450px;">
          <template #toolbar_buttons>
            <Button type="primary" @click="addSatisfactionFn">新增</Button>
          </template>
          <template #action="{ row }">
            <TableAction outside :actions="[
           {
              label:'删除',
              color: 'error',
              popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, row),
                },
             },
        ]
        " />
          </template>

        </vxe-grid>
      </template>
    </BasicForm>

  </BasicDrawer>
</template>
<script lang="ts" setup>
import {ref, computed, unref, reactive,onMounted} from 'vue';
import { BasicForm, useForm, ApiSelect } from '@/components/Form';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import {formSchema, teamUserColumns,satisfactionColumns} from './role.data';
import util from "@/utils/util";

import { useModal } from "@/components/Modal";
import { saveOfficeUser,officeChangeList,officeSatisfactionList,officeSatisfactionRemove,postRequestAll } from '@/api/sys/sysData';
import { useMessage } from "@/hooks/web/useMessage";
import { useUserStore } from "@/store/modules/user";
import {BasicTableProps} from "@/components/VxeTable";

import {Button, Descriptions, DescriptionsItem} from "ant-design-vue";
import {TableAction} from "@/components/Table";
const userStore = useUserStore();

const [registerModal, { openModal }] = useModal();

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const dataList = ref({});
const requestList =ref([]);
// const satisfactionList = ref([]);
const { createMessage } = useMessage();

const id = ref("");
const [registerForm, { resetFields, setFieldsValue, validate, clearValidate }] = useForm({
  labelWidth: 160,
  baseColProps: { lg: 8, md: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

onMounted(()=>{
  postRequestAllFn();
})

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  resetFields();
  setDrawerProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  dataList.value=data;
  tableRef2.value.reloadData([]);

  if (unref(isUpdate)) {
    id.value = data.officeUserId;
    // if(data.firstWordTime){
    //   data.firstWordTimeArr=[data.firstWordTime];
    // }
    setFieldsValue(data);
    officeChangeListFn();
    officeSatisfactionListFn();

  } else {
    //新增
    tableRef.value.reloadData([]);

  }
});

/**
 * 调岗记录表格
 */
const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: teamUserColumns,
  filterConfig: {
    remote: true,
  },
  expandConfig: {
    padding: true
  },
  showFooter: true,
  footerData: [
    { userName: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    enabled: false,
  },
});

/**
 * 满意度记录
 */
const gridOptions2 = reactive<BasicTableProps>({
  keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },//
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: satisfactionColumns,
  // filterConfig: {
  //   remote: true,
  // },
  expandConfig: {
    padding: true
  },
  showFooter: true,
  footerData: [
    { userName: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    enabled: false,
  },
});

const tableRef = ref();
const tableRef2 = ref();

const getTitle = computed(() => (!unref(isUpdate) ? '新增后勤人员' : '编辑后勤人员'));



async function handleSubmit() {
  try {
    const values = await validate();
    // let t_list = tableRef.value.getTableData().tableData;
    // values.items = t_list;
    setDrawerProps({ confirmLoading: true });
    let t_list = tableRef2.value.getTableData().tableData;

    if(t_list.length>0) {
     // console.log("--t_list:",t_list)

      for (let i = 0; i < t_list.length; i++) {
        let item= t_list[i];
        if(!item.year){
          createMessage.error(`历史业绩 ${(i+1)} 行请填写 年份`)
          return;
        }else{
          item.year=item.year.split("-01-01")[0];
        }
      }

      // t_list.forEach(item => {
      //   item.addTime=+" 00:00:00";
      // })
    }
    values.satisfactions=t_list;
    // TODO custom api
    values.officeUserId = id.value;
    if(!values.firstWordTime){
      delete values.firstWordTime;
    }
    if(!values.firstManageTime){
      delete values.firstManageTime;
    }
    if(!values.firstPostTime){
      delete values.firstPostTime;
    }
    createFn(values);
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

function createFn(values) {
  saveOfficeUser(values).then((res) => {
    // console.log("---res::",res)
    if (res.code == 200) {
      createMessage.success(res.message);

    } else {
      createMessage.error(res.message);
    }
  })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      closeDrawer();
      emit('success');
    });
}


function officeChangeListFn(){
  officeChangeList({userId:dataList.value.userId}).then((res) => {
    if(res.code == 200) {
       let arr=res.data;
       arr.forEach(item => {
         let json= JSON.parse(item.txtJson);
         let form_json= JSON.parse(json.form_component_values[0].value);
         form_json.forEach(item2 => {
           if(item2.props.label=="原职位"){
             item.original_post  =item2.value;

           }
           if(item2.props.label=="转入职位"){
             item.now_post=item2.value;
           }
         })
         console.log("---form_json:",form_json)
         item.result=json.result;
       });
       if(arr.length>0){
         tableRef.value.reloadData(arr)
         gridOptions.footerData[0].orderNo = "合计：" + arr.length + "条";
       }


    }else {
      createMessage.error(res.message);
    }
  });
}

//获取满意度
function officeSatisfactionListFn(){
  officeSatisfactionList({userId:dataList.value.userId}).then((res) => {
    if(res.code == 200) {
      let arr=res.data;

      tableRef2.value.reloadData(arr)
      gridOptions2.footerData[0].orderNo = "合计：" + arr.length + "条";

    }else {
      createMessage.error(res.message);
    }
  });
}

//添加满意度
function addSatisfactionFn(){
  let json={
    userId:dataList.value.userId,
    userName:dataList.value.userName,
  };
  tableRef2.value.insert(json)
}

function handleDelete(record: Recordable) {
  //console.log(record);
   if(record.satisfactionMainId){
     officeSatisfactionRemove(record).then(res => {
       createMessage.success(res.message);
     })
       .catch((res) => {
         createMessage.error(res.message);
       })
       .finally(() => {
         tableRef2.value.remove(record)
       });
   }else{
     tableRef2.value.remove(record)

   }

}

// function officeSatisfactionSaveBatchFn(){
//   let t_list = tableRef2.value.getTableData().tableData;
//   officeSatisfactionSaveBatch({list:t_list}).then((res) => {
//     if(res.code == 200){
//
//     }else{
//       createMessage.success(res.message);
//     }
//   })
//
// }

function postRequestAllFn(){
  postRequestAll().then(res => {
    if (res.code == 200) {
      requestList.value = res.data;
    }else{
      createMessage.error(res.message);
    }
  })
}

</script>
